I am trying to Sort Users Using lambda Expression. My Users class
public class Users
{
public long Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateCreated { get; set; }
}
And My Sorting method
public List<Users> SortUsers(string sSortBy)
{
var arg = Expression.Parameter(typeof(Users), "Users");
var body = Expression.Convert(Expression.Property(arg, sSortBy), typeof(object));
var lambda = Expression.Lambda<Func<Users, object>>(body, arg);
List<Users> UserList;
UserList = UOWUser.UsersRepository.Entities.OrderBy(lambda).ToList(); // Error here
return UserList;
}
I am Accessing the method by
List<Users> UserList;
UserList = objUsers.SortUsers("FirstName");
I am passing sSortBy as string (here "FirstName")
Error :Unable to cast the type 'System.String' to type 'System.Object'.
Comes in line UserList = UOWUser.UsersRepository.Entities.OrderBy(lambda).ToList();
Pravesh Singh
26-Mar-2014It makes the entire source.OrderBy(x => x.PropName) through Expression, so you don't have to actually specify x.PropName type.